import { IAppOption, IMenuItem, IProduct, IResultArray } from "../../../typings"
import { eventBus } from "../../utils/util"

// pages/menu/menu.ts
const app = getApp<IAppOption>()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchValue: '',
    productList: [] as IMenuItem[],
    originalProductList: [] as IMenuItem[],
    loading: true,
    specDrawerVisible: false,
    currentProduct: {} as IMenuItem,
    hasCartBar: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.fetchProducts()
    eventBus.on('cartUpdated', () => {
      // 更新页面数据，触发重新渲染购物车角标
      if (this.data.currentProduct && this.data.currentProduct._id) {
        this.getProductCartQuantity(this.data.currentProduct._id)
      }

      // 更新所有商品的购物车数量
      this.updateAllProductsCartQuantity()
    })
  },

  onPullDownRefresh() {
    this.fetchProducts()
  },

  // 打开规格选择抽屉
  openSpecDrawer(e: any) {
    const product = e.currentTarget.dataset.product
    this.setData({
      currentProduct: product,
      specDrawerVisible: true
    })
  },

  // 关闭规格选择抽屉
  onSpecDrawerClose() {
    this.setData({
      specDrawerVisible: false
    })
  },

  // 处理购物车变化事件
  onCartChange(e: any) {
    // 更新页面数据，触发重新渲染购物车角标
    if (this.data.currentProduct && this.data.currentProduct._id) {
      this.getProductCartQuantity(this.data.currentProduct._id)
    }

    // 更新所有商品的购物车数量
    this.updateAllProductsCartQuantity()
    this.setData({
      hasCartBar: app.globalData.cart.length > 0
    })
  },

  // 获取商品在购物车中的数量
  getProductCartQuantity(productId: string) {
    const cart = app.globalData.cart || []
    let quantity = 0

    // 查找所有匹配该商品ID的项，累计数量
    cart.forEach((item: any) => {
      if (item._id === productId) {
        quantity += item.quantity || 0
      }
    })
    const newProductList = this.data.productList.map(item => {
      return {
        ...item,
        quantity: item._id === productId ? quantity : item.quantity || 0
      }
    })
    this.setData({
      productList: newProductList
    })
  },

  // 更新所有商品的购物车数量
  updateAllProductsCartQuantity() {
    const cart = app.globalData.cart || []
    const productList = this.data.productList.map(product => {
      let quantity = 0

      // 查找所有匹配该商品ID的项，累计数量
      cart.forEach((item: any) => {
        if (item._id === product._id) {
          quantity += item.quantity || 0
        }
      })

      return {
        ...product,
        quantity
      }
    })

    this.setData({
      productList
    })
  },

  // 获取商品数据
  fetchProducts() {
    this.setData({
      loading: true
    })

    wx.showLoading({
      title: '加载中',
    })

    wx.cloud.callFunction({
      name: 'getProducts',
      data: {},
      success: res => {
        const result = res.result as IResultArray<IProduct>
        if (result.success && result.data.length > 0) {
          this.setData({
            productList: result.data.map(i => {
              return {
                ...i,
                quantity: 0
              }
            }),
            originalProductList: result.data.map(i => {
              return {
                ...i,
                quantity: 0
              }
            }),
            loading: false
          })

          // 更新页面数据，触发重新渲染购物车角标
          if (this.data.currentProduct && this.data.currentProduct._id) {
            this.getProductCartQuantity(this.data.currentProduct._id)
          }

          // 更新所有商品的购物车数量
          this.updateAllProductsCartQuantity()
        } else {
          this.setData({
            productList: [],
            originalProductList: [],
            loading: false
          })

          if (!result.success) {
            console.error('获取商品列表失败:', result.errMsg)
          }
        }
      },
      fail: err => {
        console.error('调用云函数失败:', err)

        this.setData({
          productList: [],
          originalProductList: [],
          loading: false
        })
      },
      complete: () => {
        wx.hideLoading()
        wx.stopPullDownRefresh()
      }
    })
  },


  // 搜索变化
  onSearchChange(e: any) {
    const value = e.detail.value
    this.setData({
      searchValue: value
    })
    this.filterProducts()
  },

  // 清除搜索
  onSearchClear() {
    this.setData({
      searchValue: '',
      productList: this.data.originalProductList
    })
  },

  // 标签切换
  onTabsChange(e: any) {
    const value = e.detail.value
    let sortedList = [...this.data.originalProductList]

    switch (value) {
      case '1': // 热销
        sortedList = sortedList.filter(item => item.isHot)
        break
      case '2': // 新品
        sortedList = sortedList.filter(item => item.isNew)
        break
      case '3': // 价格
        sortedList.sort((a, b) => a.price - b.price)
        break
      default: // 全部
        break
    }

    this.setData({
      productList: sortedList
    })
  },

  // 筛选商品
  filterProducts() {
    const { searchValue, originalProductList } = this.data
    if (!searchValue) {
      this.setData({
        productList: originalProductList
      })
      return
    }

    const filteredList = originalProductList.filter(item => {
      return item.name.includes(searchValue) || item.description.includes(searchValue)
    })

    this.setData({
      productList: filteredList
    })
  },

  // 查看商品详情
  viewProduct(e: any) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/menu/product-detail/product-detail?id=${id}`
    })
  },
})